package com.lzy.filters;

import com.lzy.context.LocalUser;
import com.lzy.security.LoginUser;
import com.lzy.utils.TokenUtil;
import com.lzy.utils.SecurityUtil;
import com.lzy.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 * 
 * @author lyw
 * @Date 2023/2/16-上午11:57
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
{

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private TokenUtil tokenUtil;

    /*
        因为 security 中出现的异常不会由全剧异常处理拦截器拦截，
        所以需要一个优先级比较高的 OncePerRequestFilter 过滤器，通过这串代码
        resolver.resolveException(request, response, null, e);
        交给全剧异常处理来拦截
     */
    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) {
        try {
            // 获取请求携带的令牌
            String token = tokenUtil.getToken(request);
            if (StringUtil.isNotEmpty(token))
            {
                // 验证 token 是否正确，刷新用户在 redis 中的过期时间
                if (tokenUtil.verifyToken(request, response, token)) {
                    // 获取token，获取 redis userKey 对应的用户信息
                    LoginUser loginUser = tokenUtil.getLoginUser(token);
                    if (StringUtil.isNotNull(loginUser)) {
                        // 保存本地用户
                        LocalUser.set(loginUser);
                        // security 的认证操作
                        // 你可以`SecurityContextHolder`直接设置而不需要使用`AuthenticationManager`
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            }
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("Spring Security Filter Chain Exception:", e);
            resolver.resolveException(request, response, null, e);
        } finally {
            LocalUser.clear();
        }
    }
}
